﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
using System.Net.Mail;
using System.Collections;
using System.Text.RegularExpressions;

public partial class main_uc_comp_det_main : DAO.ESWebUserControl
{
    public string _lang = "";
    public int logged = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        InitializeUI();
        ddl_member_type.Items.Clear();
        
        ddl_member_type.Items.Add(new ListItem(DAO.TextBaseFactory.loadText("gold_member", this.LangId), "1"));
        ddl_member_type.Items.Add(new ListItem(DAO.TextBaseFactory.loadText("silver_member", this.LangId), "2"));
        ddl_member_type.Items.Add(new ListItem(DAO.TextBaseFactory.loadText("bronze_member", this.LangId), "3"));
        ddl_member_type.Items.Add(new ListItem(DAO.TextBaseFactory.loadText("_member", this.LangId), "0"));
        ddlCountry.Attributes.Add("style", "border:solid 1px #000;");
        ddlCompanyType.Attributes.Add("style", "border:solid 1px #000;");
        cbTransportType.Attributes.Add("style", "float:left");
        if (!Page.IsPostBack)
        {
            LoadCompanyDetails();
        }
        tbLanguages.Attributes.Add("multiple", "multiple");
    }

    private void LoadCompanyDetails()
    {
        if (Request.QueryString["cid"] != null && Request.QueryString["cid"] != "")
        {
            using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM Fn_CompById(@id,@language_id)", conn))
                {
                    int cid = 0;
                    Int32.TryParse(Request.QueryString["cid"].ToString(), out cid);
                    cmd.Parameters.Add("id", cid);
                    cmd.Parameters.Add("@language_id", this.LangId);
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.Read())
                    {
                        //set image
                        if (dr["fileimage"].ToString() != "")
                        {
                            string path = dr["id"].ToString() + "_" + dr["fileimage"].ToString();
                            if (File.Exists(Server.MapPath("~/images/company/" + path)))
                                imgLogo.ImageUrl = "~/images/company/" + path;
                        }
                        if (dr["company_status"].ToString() == "1")
                        {
                            cbIsActive.Attributes.Add("active", "1");
                            cbIsActive.Checked = true;
                        }
                        else cbIsActive.Attributes.Add("active", "0");
                        if (Request.Cookies["texchange"] != null && Request.Cookies["texchange"]["logged"] != null && DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["logged"]) == "true"
                            && (DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["type"].ToString()) == "admin" || DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["cid"].ToString()) == cid.ToString()))
                        {
                            logged = 1;
                            //load za update
                            tbAddress.Text = dr["address"].ToString();
                            if (DAO.UserManagement.getUserStatus(cid))
                            {
                                lbl_OnlineStatus.Text = "Online";
                                lbl_OnlineStatus.ForeColor = System.Drawing.Color.FromArgb(0, 255, 0);
                            }
                            else
                            {
                                lbl_OnlineStatus.Text = "Offline";
                                lbl_OnlineStatus.ForeColor = System.Drawing.Color.FromArgb(255, 0, 0);
                            }
                            tbAddress.Attributes.Add("validate", "true");
                            tbCity.Text = dr["City"].ToString();
                            if (dr["operating_licence"].ToString() != "")
                            {
                                if (File.Exists(Server.MapPath("~/images/op_licence/op_" + dr["id"].ToString() + "_" + dr["operating_licence"].ToString())))
                                {
                                    fuOpLicence.Enabled = false;
                                    hlOperatingLicence.Visible = true;
                                    hlOperatingLicence.Text = "licence";
                                    hlOperatingLicence.NavigateUrl = "~/images/op_licence/op_" + dr["id"].ToString() + "_" + dr["operating_licence"].ToString();
                                }
                                else
                                    hlOperatingLicence.Visible = false;
                            }
                            else fuOpLicence.Enabled = true;
                            tbCity.Attributes.Add("validate", "true");
                            using (SqlCommand cmdComp = new SqlCommand("SELECT * from Fn_GetUniversalTypeById(" + dr["type_company_id"] + "," + this.LangId + ")", conn))
                            {
                                SqlDataReader drcomp = cmdComp.ExecuteReader();
                                string type_company_id = "0";
                                if (drcomp.Read())
                                {
                                    type_company_id = drcomp["id"].ToString();
                                }
                                LoadCompanyType(this.LangId);
                                ddlCompanyType.SelectedValue = type_company_id;
                                drcomp.Close();
                            }
                            tbCompName.Text = dr["name"].ToString();
                            tbCompName.Attributes.Add("validate", "true");
                            string country_id = dr["country_id"].ToString();
                            LoadCountry();
                            ddlCountry.SelectedValue = country_id;
                            tbOperatingActivity.Text = dr["operating_activity"].ToString();
                            tb_tax_file_number.Text = dr["tax_file_number"].ToString();
                            //tbOperatingLicence.Text = dr["operating_licence"].ToString();
                            tbPostCode.Text = dr["postcode"].ToString();
                            //lblTransportType.Text = dr["address"].ToString();
                            LoadTransportType(this.LangId);
                            using (SqlCommand cmdCompT = new SqlCommand("SP_TransportTypesByCompany", conn))
                            {
                                cmdCompT.CommandType = System.Data.CommandType.StoredProcedure;
                                cmdCompT.Parameters.Add("id", cid);
                                cmdCompT.Parameters.Add("language_id", this.LangId);
                                SqlDataReader drcompT = cmdCompT.ExecuteReader();
                                while (drcompT.Read())
                                {
                                    ListItem l = cbTransportType.Items.FindByValue(drcompT["id"].ToString());
                                    if (l != null) l.Selected = true;
                                }
                                drcompT.Close();
                            }
                            ESi18nButton1.TextReference = "save";
                            if (dr["member_type_id"] != null)
                            {
                                ddl_member_type.SelectedValue = dr["member_type_id"].ToString();
                                switch (dr["member_type_id"].ToString())
                                {
                                    case "1":
                                        lblMember.Text = DAO.TextBaseFactory.loadText("gold_member", this.LangId);
                                        break;
                                    case "2":
                                        lblMember.Text = DAO.TextBaseFactory.loadText("silver_member", this.LangId);
                                        break;
                                    case "3":
                                        lblMember.Text = DAO.TextBaseFactory.loadText("bronze_member", this.LangId);
                                        break;
                                    case "0":
                                        lblMember.Text = DAO.TextBaseFactory.loadText("_member", this.LangId);
                                        break;
                                    default:
                                        lblMember.Text = DAO.TextBaseFactory.loadText("_member", this.LangId);
                                        break;
                                }
                            }
                            
                            //contact details
                            tbTelephone.Text = dr["telephone"].ToString();
                            tbFax.Text = dr["fax"].ToString();
                            tbMobile.Text = dr["mobile"].ToString();
                            tbWebsite.Text = dr["website"].ToString();
                            tbExt.Text = dr["ext"].ToString();
                            tbContactPerson.Text = dr["contact_person"].ToString();
                            LoadLangs();
                            if (dr["language"] != null && dr["language"].ToString()!="")
                            {
                                if (dr["language"].ToString().Length>2)
                                _lang = dr["language"].ToString().Substring(0, dr["language"].ToString().Length - 1);
                                hf_lang.Value = _lang;
                            }
                            string[] _langs = _lang.Split(',');
                            foreach (ListItem l in tbLanguages.Items)
                            {
                                if (_langs.Contains(l.Value))
                                {
                                    l.Attributes.Add("selected", "selected");
                                }
                            }
                            tbJobTitle.Text = dr["job_title"].ToString();
                            tb_email.Text = dr["email"].ToString();
                            //lbl_passAdmin.Text = dr["email"].ToString();
                            tbCompName.Enabled = false;
                            ddlCountry.Enabled = false;
                            ddlCompanyType.Enabled = false;
                            if (DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["type"].ToString()) == "admin")
                            {
                                cbIsActive.Visible = true;
                                ddl_member_type.Visible = true;
                                lblMember.Visible = false;
                                ESi18nButton2.Visible = true;
                                tb_email.Visible = true;
                                ESi18nLabel29.Visible = true;
                                tbCompName.Enabled = true;
                                ddlCountry.Enabled = true;
                                ddlCompanyType.Enabled = true;
                                tb_tax_file_number.Enabled = true;
                                tb_tax_file_number.Visible = true;
                            }
                        }
                        else
                        {
                            //load samo labeli
                            lblAddress.Text = dr["address"].ToString();
                            lblCity.Text = dr["City"].ToString();
                            using (SqlCommand cmdComp = new SqlCommand("SELECT * from Fn_GetUniversalTypeById(" + dr["type_company_id"] + "," + this.LangId + ")", conn))
                            {
                                SqlDataReader drcomp = cmdComp.ExecuteReader();
                                if (drcomp.Read())
                                {
                                    lblCompanyType.Text = drcomp["name"].ToString();
                                }
                                drcomp.Close();
                            }
                            lblCompName.Text = dr["name"].ToString();
                            lblCountry.Text = "<img height='12' width='20' src='images/countries/" + dr["short"].ToString() + "-t.gif' title='" + dr["country"].ToString() + "' />&nbsp;&nbsp;" + dr["short"].ToString() + " - " + dr["country"].ToString();
                            //lblOperatingActivity.Text = dr["operating_activity"].ToString();
                            //lblOperatingLicence.Text = dr["operating_licence"].ToString();
                            lblPostCode.Text = dr["postcode"].ToString();
                            //lblTransportType.Text = dr["address"].ToString();
                            using (SqlCommand cmdCompT = new SqlCommand("SP_TransportTypesByCompany", conn))
                            {
                                cmdCompT.CommandType = System.Data.CommandType.StoredProcedure;
                                cmdCompT.Parameters.Add("id", cid);
                                cmdCompT.Parameters.Add("language_id", this.LangId);
                                SqlDataReader drcompT = cmdCompT.ExecuteReader();
                                while (drcompT.Read())
                                {
                                    lblTransportType.Text += drcompT["name"] + "<br>";
                                }

                                drcompT.Close();
                            }
                            switch (dr["member_type_id"].ToString())
                            {
                                case "0":
                                    lblMember.Text = DAO.TextBaseFactory.loadText("_member", this.LangId);
                                    break;
                                case "1":
                                    lblMember.Text = DAO.TextBaseFactory.loadText("gold_member", this.LangId);
                                    break;
                                case "2":
                                    lblMember.Text = DAO.TextBaseFactory.loadText("silver_member", this.LangId);
                                    break;
                                case "3":
                                    lblMember.Text = DAO.TextBaseFactory.loadText("bronze_member", this.LangId);
                                    break;
                                default:
                                    lblMember.Text = DAO.TextBaseFactory.loadText("_member", this.LangId);
                                    break;
                            }
                            
                            lblTelephone.Text = dr["ext"].ToString() + " " + dr["telephone"].ToString();
                            lblFax.Text = dr["fax"].ToString();
                            lblMobile.Text = dr["mobile"].ToString();
                            lblWebsite.Text = dr["website"].ToString();
                            lblContactPerson.Text = dr["contact_person"].ToString();
                            LoadLangsByIds(dr["language"].ToString());
                            lblJobTitle.Text = dr["job_title"].ToString();

                            /*if (File.Exists(Server.MapPath("~/images/op_licence/op_" + dr["id"].ToString() + "_" + dr["operating_licence"].ToString())))
                            {
                                hlOperatingLicence.Visible = true;
                                hlOperatingLicence.Text = "licence";
                                hlOperatingLicence.NavigateUrl = "~/images/op_licence/op_" + dr["id"].ToString() + "_" + dr["operating_licence"].ToString();
                            }
                            else
                                hlOperatingLicence.Visible = false;*/
                            fuOpLicence.Visible = false;
                            tbExt.Visible = false;
                            tbAddress.Visible = false;
                            tbCity.Visible = false;
                            ph_changepass.Visible = false;
                            tbCompName.Visible = false;
                            tbOperatingActivity.Visible = false;
                            //tbOperatingLicence.Visible = false;
                            tbPostCode.Visible = false;
                            ddlCompanyType.Visible = false;
                            ddlCountry.Visible = false;
                            cbTransportType.Visible = false;
                            tbTelephone.Visible = false;
                            tbFax.Visible = false;
                            tbMobile.Visible = false;
                            tbWebsite.Visible = false;
                            tbContactPerson.Visible = false;
                            tbLanguages.Visible = false;
                            tbJobTitle.Visible = false;
                            fuImage.Visible = false;
                            ESi18nButton2.Visible = false;
                        }
                        dr.Close();
                        if (Request.Cookies["texchange"] != null && Request.Cookies["texchange"]["logged"] == null)
                        {
                            ESi18nButton1.Visible = false;
                        }
                    }
                }
            }
        }
        else Response.Redirect("~/Default.aspx");
    }

    private void LoadLangs()
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Fn_GetAllPlaces(0, 1000000, 'id', 'asc', 4) WHERE isActive='true' Order By name asc", conn))
            {
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    tbLanguages.Items.Add(new ListItem(dr["short"].ToString().ToUpper() + " - " + dr["name"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

    private void LoadLangsByIds(string ids)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            if (ids != "," && ids != "")
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Fn_GetAllPlaces(0, 1000000, 'id', 'asc', 4) WHERE id IN (" + ids.Substring(0, ids.Length - 1) + ")", conn))
                {
                    SqlDataReader dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        lblLanguages.Text += dr["short"].ToString().ToUpper() + " - " + dr["name"].ToString() + ", ";
                    }
                    dr.Close();
                }
            }
        }
    }


    private void LoadCountry()
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT id, short, name FROM dbo.Fn_GetAllPlaces(0, 1000000, 'id', 'asc', 2) WHERE isActive='true'", conn))
            {
                SqlDataReader dr = cmd.ExecuteReader();
                ddlCountry.Items.Add(new ListItem("", "0"));
                while (dr.Read())
                {
                    ddlCountry.Items.Add(new ListItem(dr["name"].ToString() + " - " + dr["short"].ToString(), dr["id"].ToString()));
                }
                dr.Close();
            }
        }
    }

    protected override void InitializeUI()
    {
        long langId = DAO.Connection.DEFAULT_LANGUAGE;
        if (Session["language"] != null)
            long.TryParse(Session["language"].ToString(), out langId);

        this.LangId = Convert.ToInt32(langId);
    }

    private void LoadCompanyType(int lang)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Fn_GetAllUniversalTypes(0, 1000000, 'id', 'asc', 2, " + lang + ") WHERE isActive='true'", conn))
            {
                SqlDataReader dr = cmd.ExecuteReader();
                if (lang == DAO.Connection.DEFAULT_LANGUAGE)
                {
                    while (dr.Read())
                    {
                        ddlCompanyType.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                    }
                }
                else
                {
                    while (dr.Read())
                    {
                        ddlCompanyType.Items.Add(new ListItem(dr["name"].ToString(), dr["parent_id"].ToString()));
                    }
                }
                dr.Close();
            }
        }
    }

    private void LoadTransportType(int lang)
    {
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Fn_GetAllUniversalTypes(0, 1000000, 'id', 'asc', 7, " + lang + ") WHERE isActive='true'", conn))
            {
                SqlDataReader dr = cmd.ExecuteReader();
                //ddlTypeTransport.Items.Add(new ListItem("", "0"));
                if (lang == DAO.Connection.DEFAULT_LANGUAGE)
                {
                    while (dr.Read())
                    {
                        if (dr["id"].ToString() != "40" && dr["id"].ToString() != "41" && dr["id"].ToString() != "42")
                            cbTransportType.Items.Add(new ListItem(dr["name"].ToString(), dr["id"].ToString()));
                    }
                }
                else
                {
                    while (dr.Read())
                    {
                        if (dr["parent_id"].ToString() != "40" && dr["parent_id"].ToString() != "41" && dr["parent_id"].ToString() != "42")
                            cbTransportType.Items.Add(new ListItem(dr["name"].ToString(), dr["parent_id"].ToString()));
                    }
                }
                dr.Close();
            }
        }
    }

    protected void ESi18nButton1_Click(object sender, EventArgs e)
    {
        if (ESi18nButton1.TextReference == "save")
        {
            //then save
            long cid =0;
            try
            {
                Int64.TryParse(Request.QueryString["cid"].ToString(), out cid);
            }
            catch(Exception ex){
                
            }
            if (cid > 0)
            {
                long userid;
                if (ValidateForm(out userid))
                {
                    using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
                    {
                        conn.Open();
                        using (SqlCommand cmd = new SqlCommand("SP_UpdateComp", conn))
                        {
                            cmd.Parameters.Add("id", cid);
                            cmd.Parameters.Add("name", tbCompName.Text);
                            cmd.Parameters.Add("country_id", ddlCountry.SelectedValue);
                            cmd.Parameters.Add("city", tbCity.Text);
                            cmd.Parameters.Add("postcode", tbPostCode.Text);
                            cmd.Parameters.Add("address", tbAddress.Text);
                            cmd.Parameters.Add("type_company_id", ddlCompanyType.SelectedValue);
                            cmd.Parameters.Add("operating_activity", tbOperatingActivity.Text);
                            cmd.Parameters.Add("tax_file_number", tb_tax_file_number.Text);
                            if (cbIsActive.Visible == false)
                                cmd.Parameters.AddWithValue("company_status", 1);
                            else
                            {
                                if (cbIsActive.Checked)
                                    cmd.Parameters.AddWithValue("company_status", 1);
                                else cmd.Parameters.AddWithValue("company_status", 0);
                            }
                            if (ddl_member_type.Visible == true)
                                cmd.Parameters.AddWithValue("member_type_id", ddl_member_type.SelectedValue);
                            else
                            {
                                cmd.Parameters.AddWithValue("member_type_id", 3);
                            }
                            cmd.Parameters.Add("telephone", tbTelephone.Text);
                            cmd.Parameters.Add("ext", tbExt.Text);
                            cmd.Parameters.Add("fax", tbFax.Text);
                            cmd.Parameters.Add("mobile", tbMobile.Text);
                            cmd.Parameters.Add("website", tbWebsite.Text);
                            cmd.Parameters.Add("contact_person", tbContactPerson.Text);
                            cmd.Parameters.Add("language", hf_lang.Value + ",");
                            cmd.Parameters.Add("job_title", tbJobTitle.Text);
                            cmd.Parameters.Add("email", tb_email.Text);

                            cmd.CommandType = System.Data.CommandType.StoredProcedure;
                            object val = null;
                            try
                            {
                                val = cmd.ExecuteNonQuery();
                                if (cbIsActive.Attributes["active"] == "0" && cbIsActive.Checked)
                                    SendMailToUser(cid);
                            }
                            catch (Exception ex)
                            {
                                Session["message"] = "error in update " + ex.ToString();
                            }
                            if (val != null)
                            {
                                //Update user password
                                if (tb_new_pass.Text != "" && userid != -1)
                                {
                                    using (SqlCommand cmd_updatepass = new SqlCommand("SP_UpdateUserPass", conn))
                                    {
                                        cmd_updatepass.Parameters.AddWithValue("userid", userid);
                                        cmd_updatepass.Parameters.AddWithValue("password", DAO.CodeFactory.CalcMD5String(tb_new_pass.Text));
                                        cmd_updatepass.CommandType = System.Data.CommandType.StoredProcedure;
                                        try
                                        {
                                            cmd_updatepass.ExecuteNonQuery();
                                            Session["message"] = "Update was succesfull";
                                            Session["message_type_css"] = "par_message_ok";
                                        }
                                        catch (Exception ex)
                                        {
                                            Session["message"] = "There was an error updateing the information. Reason " + ex.ToString();
                                            Session["message_type_css"] = "par_message_error";
                                        }
                                    }
                                }
                                //update Transport activity
                                //first delete all transport activity information for this company
                                cmd.Parameters.Clear();
                                cmd.CommandText = "DELETE from CJCompanyTransport WHERE company_id=" + cid;
                                cmd.CommandType = System.Data.CommandType.Text;
                                object valCJ = null;
                                try
                                {
                                    valCJ = cmd.ExecuteNonQuery();
                                }
                                catch (Exception ex)
                                {
                                    Session["message"] = "error in update " + ex.ToString();
                                }
                                if (valCJ != null)
                                {
                                    //insert new values for transport activity
                                    foreach (ListItem l in cbTransportType.Items)
                                    {
                                        if (l.Selected)
                                        {
                                            cmd.Parameters.Clear();
                                            cmd.CommandText = "SP_InsCJCompanyTransport";
                                            cmd.CommandType = System.Data.CommandType.StoredProcedure;
                                            cmd.Parameters.Add(new SqlParameter("company_id", cid));
                                            cmd.Parameters.Add(new SqlParameter("transporttype_id", l.Value));
                                            int cj = 0;
                                            try
                                            {
                                                Int32.TryParse(cmd.ExecuteScalar().ToString(), out cj);
                                            }
                                            catch (Exception ex)
                                            {
                                                Session["message"] = "error in update " + ex.ToString();
                                            }
                                        }
                                    }
                                }
                                if (fuImage.FileName != "")
                                {
                                    string pathItem = "~/images/company/" + cid + "_" + fuImage.FileName;
                                    Stream st_item = fuImage.PostedFile.InputStream;
                                    int st_item_size = (int)st_item.Length;
                                    FileStream fs_item = new FileStream(Server.MapPath(pathItem), FileMode.Create, FileAccess.Write);
                                    byte[] arr_item = new byte[st_item_size];
                                    st_item.Read(arr_item, 0, st_item_size);
                                    fs_item.Write(arr_item, 0, st_item_size);
                                    fs_item.Close();
                                    cmd.Parameters.Clear();
                                    cmd.CommandText = "UPDATE Company SET fileimage = '" + fuImage.FileName + "' WHERE id=" + cid;
                                    cmd.CommandType = System.Data.CommandType.Text;
                                    object v = cmd.ExecuteNonQuery();
                                }
                                if (fuOpLicence.FileName != "")
                                {
                                    string pathItem = "~/images/op_licence/op_" + cid + "_" + fuOpLicence.FileName;
                                    Stream st_item = fuOpLicence.PostedFile.InputStream;
                                    int st_item_size = (int)st_item.Length;
                                    FileStream fs_item = new FileStream(Server.MapPath(pathItem), FileMode.Create, FileAccess.Write);
                                    byte[] arr_item = new byte[st_item_size];
                                    st_item.Read(arr_item, 0, st_item_size);
                                    fs_item.Write(arr_item, 0, st_item_size);
                                    fs_item.Close();
                                    cmd.Parameters.Clear();
                                    cmd.CommandText = "UPDATE Company SET operating_licence = '" + fuOpLicence.FileName + "' WHERE id=" + cid;
                                    cmd.CommandType = System.Data.CommandType.Text;
                                    object v = cmd.ExecuteNonQuery();
                                }
                            }
                        }
                    }
                }
            }
            Response.Redirect(Request.Url.ToString());
        }
        else
        {
            //add to my favorites
            long cid = 0;
            try
            {
                Int64.TryParse(Request.QueryString["cid"].ToString(), out cid);
            }
            catch (Exception ex)
            {
                
            }

            long userid = 0;
            try
            {
                Int64.TryParse(DAO.GlobalSettings.Decrypt(Request.Cookies["texchange"]["cid"].ToString()), out userid);
            }
            catch (Exception ex)
            {

            }
            if (cid > 0 && userid > 0)
            {
                using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand("SELECT id from Favorites WHERE company_id=@cid and favorite_id=@fav_id", conn))
                    {
                        cmd.Parameters.Add("cid", userid);
                        cmd.Parameters.Add("fav_id", cid);

                        object fvId = null;
                        try
                        {
                            fvId = cmd.ExecuteScalar();
                        }
                        catch { }
                        if (fvId == null)
                        {
                            using (SqlCommand cmd1 = new SqlCommand("INSERT INTO Favorites VALUES(@cid, @fav_id)", conn))
                            {
                                cmd1.Parameters.Clear();
                                cmd1.Parameters.Add("cid", userid);
                                cmd1.Parameters.Add("fav_id", cid);
                                object val = null;
                                try
                                {
                                    val = cmd1.ExecuteScalar();
                                }
                                catch (Exception ex)
                                {
                                    //
                                }
                                if (val != null)
                                {
                                    //success
                                }
                                else
                                {
                                    //problem
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    //return the userid because we don't want to cann one procedure twice
    private bool ValidateForm(out long userid)
    {
        userid = -1;
        string old_pass = tb_oldpass.Text;
        string new_pass = tb_new_pass.Text;
        string new_repeat_pass = tb_new_pass_repeat.Text;

        if (old_pass != "")//validate change password
        {
            using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
            {
                conn.Open();
                long cust_id = Convert.ToInt64(Request.QueryString["cid"].ToString());
                using (SqlCommand cmd = new SqlCommand("SELECT id, username, password FROM Users WHERE company_id=" + cust_id, conn))
                {
                    SqlDataReader dr = null;
                    dr = cmd.ExecuteReader();
                    if (dr != null && dr.HasRows)
                    {
                        dr.Read();
                        userid = Convert.ToInt64(dr["id"].ToString());
                        if (dr["password"].ToString() == DAO.CodeFactory.CalcMD5String(old_pass))
                        {
                            if (old_pass != "" && new_pass != "")
                            {
                                if (old_pass != new_pass)
                                {
                                    if (new_pass == new_repeat_pass)
                                    {
                                        Regex strongpass = new Regex("");
                                        if(Regex.IsMatch(new_pass, @"^.{6,}(?<=\d.*)(?<=[^a-zA-Z0-9].*)$"))
                                        {
                                            return true;
                                        }
                                        else
                                        {
                                            Session["message"] = "The password should be at least 8 characters long and should contain set of letters and numbers";
                                            return false;
                                        }
                                    }
                                    else
                                    {
                                        Session["message"] = "The New Password and Repeat new password are not equal";
                                        return false;
                                    }
                                }
                                else
                                {
                                    Session["message"] = "Old password and new password are the same";
                                    return false;
                                }
                            }
                            else
                            {
                                Session["message"] = "Please input values for new password and repeat new password";
                                return false;
                            }
                        }
                        else
                        {
                            Session["message"] = "The old password is incorrect";
                            return false;
                        }
                    }
                    else
                    {
                        Session["message"] = "The user doesn't exist in the database. Please contact the system administrator!";
                        return false;
                    }
                }
            }
        }

        return true;
    }

    private void SendMailToUser(long id)
    {
        string senderMailAdress = ConfigurationManager.AppSettings["senderMailAdress"].ToString();
        string host = ConfigurationManager.AppSettings["host"].ToString();
        //string username = ConfigurationManager.AppSettings["username"].ToString();
        //string password = ConfigurationManager.AppSettings["password"].ToString();

        //create new mail message
        MailMessage mail = new MailMessage();

        //create mail message body
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        mail.IsBodyHtml = true;
        mail.BodyEncoding = System.Text.Encoding.UTF8;

        sb.Append("<html><head>");
        sb.Append("<style> body{font-family: \"Calibri\",\"sans-serif\";font-size: 11pt;margin: 0 0 0.0001pt;}</style>");
        sb.Append("</head><body>");

        sb.Append("<center><span style='font-size:16px'><b>WELCOME TO TRANSPORT EXCHANGE<b></span></center>");
        sb.Append("<b>www.TransportExchange.org</b>");
        sb.Append("<br><br>");
        sb.Append("Thank you for taking the time to register. ");
        sb.Append("<br>");
        sb.Append("<p>We are pleased to advise you that <b>your registration is under review.</b></p>");
        sb.Append("<p>Your status is: ACTIVE</p>");
        sb.Append("<p>You are now a member of the international Transport Exchange network.</p>");
        string email = "";
        using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand("SELECT username, orig_pass FROM Users WHERE company_id=" + id, conn))
            {
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    sb.Append("<p>Username: "+dr["username"]+"</p>");
                    sb.Append("<p>Password: " + dr["orig_pass"] + "</p>");
                    email = dr["username"].ToString();
                }
                dr.Close();
            }
        }
        sb.Append("<p>COMPANY INFORMATION:</p>");
        sb.Append("<strong>Company name:</strong> <br>");

        sb.Append("<p>In order for us to endorse your membership, we need you to submit via fax or email the following documents, within 30 days from today:</p>");
        sb.Append("<p>• Copy of your company’s operating license (if applicable), or a document for registration of legal entity for your company.</p>");
        sb.Append("<p>We need these documents in order for us to establish whether you are a legitimate, registered business. This safety feature ensures that all our clients, including you, are protected from fraudulent companies or spammers. We will NEVER disclose these documents to Third Parties, and we will securely store them in our system only for the duration of your membership.</p>");
        sb.Append("<br>");
        sb.Append("<p>Thank you for your interest in becoming a member. </p>");
        sb.Append("<br><br>");
        sb.Append("<center><span style='font-size:16px'><b>WELCOME TO TRANSPORT EXCHANGE<b></span></center>");
        sb.Append("<br><br>");
        sb.Append("<p style='font-size:16px'><b>Transport Exchange</b></p>");
        sb.Append("<p>Str. 710 No. 1 1000 Skopje - Macedonia</p>");
        sb.Append("<p>Tel +389 2 2551 057 </p>");
        sb.Append("<p>Fax +389 2 2549 016 </p>");
        sb.Append("<p>Cell. Tel. +389 78399019 </p>");
        sb.Append("<p>e-mail: <a href='mailto:info@transportexchange.org'>info@transportexchange.org</a> </p>");
        sb.Append("<p>skype: transportexchange</p>");
        sb.Append("<p>Website: <a href='http://www.transportexchange.org'>www.transportexchange.org</a></p>");
        sb.Append("</body></html>");
        mail.Body = sb.ToString();

        //set mail message properties
        if (email != "")
            mail.To.Add(new MailAddress(email));
        //mail.Bcc.Add("ratkop@gmail.com");
        mail.From = new MailAddress(senderMailAdress);
        mail.Subject = "TransportExchange.org Registration";

        //create new SmtpClient
        SmtpClient smtpClient = new SmtpClient();

        //set SmtpClient properties
        smtpClient.Port = 25;
        smtpClient.Host = host;
        // for example gmail smtp server
        //smtpClient.Port = Convert.ToInt32(ConfigurationManager.AppSettings["port"]);
        string username = ConfigurationManager.AppSettings["username"].ToString();
        string password = ConfigurationManager.AppSettings["password"].ToString();
        smtpClient.Credentials = new System.Net.NetworkCredential(username, password);

        //send mail message
        try
        {
            if (email != "") smtpClient.Send(mail);
        }
        catch (Exception ex)
        {
        }
    }
    /// <summary>
    /// Delete Company
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ESi18nButton2_Click(object sender, EventArgs e)
    {
        try
        {
            if (Request.QueryString["cid"] != null && Request.QueryString["cid"] != "")
            {
                using (SqlConnection conn = new SqlConnection(DAO.Connection.CONN_STRING1))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand("SP_DeleteCompany", conn))
                    {
                        int cid = 0;
                        if (Int32.TryParse(Request.QueryString["cid"].ToString(), out cid))
                        {
                            cmd.Parameters.Add("id", cid);
                            cmd.CommandType = System.Data.CommandType.StoredProcedure;
                            cmd.ExecuteNonQuery();
                            SqlCommand cmd_deleteUser = new SqlCommand("DELETE FROM Users WHERE company_id=" + cid, conn);
                            cmd_deleteUser.ExecuteNonQuery();
                            Response.Redirect("~/Company.aspx");
                        }
                    }
                }
            }
        }
        catch(Exception ex)
        {
            //Response.Write(ex.Message);
        }
    }
}
